package com.hoo.permission.sdk.server.dao.impl;

import com.hoo.permission.sdk.server.dao.ISysUserResourceDao;
import com.hoo.permission.sdk.server.domain.entity.SysUserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户-资源关系表（适用于弱角色场景、减少角色处理场景) Dao层 实现
 * 删减用户和删减资源时需使用
 * @author 小韩工作室
 * @date 2020-08-09 17:19:00
 */
@Repository
public class SysUserResourceDaoImpl implements ISysUserResourceDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /*@Override
    public boolean add(SysUserResource entity){
        return jdbcTemplate.update("INSERT INTO sys_user_resource(user_id, resource_id) VALUES(?, ?)", entity.getUserId(), entity.getResourceId()) > 0;
    }

    @Override
    public boolean delete(SysUserResource entity){
        return jdbcTemplate.update("DELETE FROM sys_user_resource WHERE user_id = ?, resource_id = ?", entity.getUserId(), entity.getResourceId()) > 0;
    }*/

    @Override
    public boolean add(Long userId, List<Long> resourceIds) {
        List<Object[]> list = new ArrayList<>();
        if (resourceIds != null && userId != null && resourceIds.size() > 0) {
            for (Long resourceId : resourceIds) {
                list.add(new Long[] {userId, resourceId});
            }
            return jdbcTemplate.batchUpdate("INSERT INTO t_sys_user_resource(user_id, resource_id) VALUES(?, ?)", list).length == resourceIds.size();
        }
        return false;
    }

    @Override
    public boolean deleteByUserId(Long userId) {
        return jdbcTemplate.update("DELETE FROM t_sys_user_resource WHERE user_id = ?", userId) > 0;
    }

    @Override
    public boolean deleteByResourceId(Long resourceId) {
        return jdbcTemplate.update("DELETE FROM t_sys_user_resource WHERE resource_id = ?", resourceId) > 0;
    }

    @Override
    public boolean batchDeleteByResourceIds(List<Long> resourceIds) {
        List<Object[]> list = new ArrayList<>();
        if (resourceIds != null && resourceIds.size() > 0) {
            for (Long resourceId : resourceIds) {
                list.add(new Long[] {resourceId});
            }
            return jdbcTemplate.batchUpdate("DELETE FROM t_sys_user_resource WHERE resource_id = ?", list).length == resourceIds.size();
        }
        return false;
    }

    @Override
    public List<Long> getResourcesByUserId(Serializable userId) {
        List<Long> resourceIds = jdbcTemplate.queryForList("SELECT resource_id FROM t_sys_user_resource WHERE user_id = ?", new Object[]{userId}, Long.class);
        return resourceIds == null ? new ArrayList<>() : resourceIds;
    }

}
